import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { ListView } from 'antd-mobile';
import AlbumItem from '../components/AlbumItem';
import BackTop from '../components/BackTop';
import { getAlbumList, getAlbumGroupById } from '../utils';

// 主界面专辑列表
class HomeAlbumList extends Component {

    constructor(props, context) {
        super(props, context);
        const ds = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });

        this.onHandlePlayAudio = this.onHandlePlayAudio.bind(this);
        this.onScroll = this.onScrollListen.bind(this);
        this.handleScrollToClick = this.handleScrollToClick.bind(this);
        this.albumItemClick = this.albumItemClick.bind(this);

        const groupId = this.props.groupId;
        this.latestId = 0;
        this.albums = [];
        if (this.props.category_id) {
            // 读取缓存中的数据
            let category_id = sessionStorage.getItem('category_id');
            this.scrollY = 0;
            if (category_id && parseInt(category_id, 10) === this.props.category_id) {
                const cacheAlbumList = sessionStorage.getItem('albums');
                if (cacheAlbumList) {
                    this.albums = JSON.parse(cacheAlbumList);
                    const lastAlbum = this.albums[this.albums.length - 1];
                    this.latestId = lastAlbum.id;
                    const scrollY = sessionStorage.getItem('scrollY');
                    if (scrollY) {
                        this.scrollY = parseInt(scrollY, 10);
                    }
                }
            }
        }

        this.state = {
            albums: this.albums,
            latestId: this.latestId,
            groupId: groupId,
            dataSource: ds.cloneWithRows(this.albums),
            height: document.documentElement.clientHeight * 3, // 高度
            isLoading: true,
            hasMore: true,
            hiddenBackTop: true,
        };
    }
    componentDidMount() {
        this._isMounted = true;
        let hei = document.documentElement.clientHeight - ReactDOM.findDOMNode(this.lv).parentNode.offsetTop;
        this.setState({
            height: hei,
        });

        if (this.albums.length === 0) {
            this.fetch()
        } else {
            setTimeout(() => {
                this.lv.scrollTo(0, this.scrollY);
            }, 200);
        }
    }

    componentWillUnmount() {
        this._isMounted = false;
    }

    fetch() {
        if (this.state.groupId) {
            // 点击更多进入之后,仅仅展示分组栏的数据
            getAlbumGroupById(this.state.groupId, this.state.latestId, (function (data) {
                if (!this._isMounted) {
                    return;
                }
                if (data.errcode === 0) {
                    let len = data.data.length
                    if (len > 0) {
                        let albums = this.state.albums.concat(data.data)
                        this.setState({
                            albums: albums
                        });
                        let hasMore = (len === 20);
                        this.setState({
                            dataSource: this.state.dataSource.cloneWithRows(albums),
                            hasMore: hasMore,
                            isLoading: false,
                            latestId: data.data[len - 1].id,
                        });

                    } else {
                        this.setState({ isLoading: false, hasMore: false });
                    }
                } else {
                    this.setState({ isLoading: false, });
                }
            }).bind(this));

        } else {
            getAlbumList(this.props.category_id, this.state.latestId, (function (data) {
                if (!this._isMounted) {
                    return;
                }
                if (data.errcode === 0) {
                    let len = data.data.length
                    if (len > 0) {
                        let albums = this.state.albums.concat(data.data)
                        this.setState({
                            albums: albums
                        });
                        let hasMore = (len === 20);
                        this.setState({
                            dataSource: this.state.dataSource.cloneWithRows(albums),
                            hasMore: hasMore,
                            isLoading: false,
                            latestId: data.data[len - 1].id,
                        });

                    } else {
                        this.setState({ isLoading: false, hasMore: false });
                    }
                } else {
                    this.setState({ isLoading: false, });
                }
            }).bind(this));
        }
    }

    onHandlePlayAudio(audio) {
        this.props.onHandlePlayAudio(audio);
    }

    albumItemClick(album) {
        if (this.props.category_id) {
            sessionStorage.setItem('category_id', this.props.category_id);
            sessionStorage.setItem('albums', JSON.stringify(this.state.albums));
        }
        this.props.albumItemClick(album);
    }

    handleScrollToClick() {
        this.lv.scrollTo(0, 0)
    }

    onScrollListen(event) {
        const offset = event.target.scrollTop;
        if (offset > 100) {
            if (this.state.hiddenBackTop) {
                this.setState({ hiddenBackTop: false });
            }
        } else if (offset <= 100 && !this.state.hiddenBackTop) {
            setTimeout(() => {
                this.setState({ hiddenBackTop: true });
            }, 500)
        }
        sessionStorage.setItem('scrollY', offset);
    }

    onEndReached = (event) => {
        if (this.state.isLoading === true
            && this.state.hasMore === false) {
            return;
        }
        this.setState({ isLoading: true });
        this.fetch();
    }

    render() {
        const row = (rowData, sectionID, rowID) => {
            return (
                <AlbumItem key={rowID} album={rowData} albumItemClick={this.albumItemClick} />
            );
        };
        return (
            <div>
                {
                    this.props.category_id !== 5 &&
                    <BackTop handleClick={this.handleScrollToClick} hidden={this.state.hiddenBackTop} />
                }

                <ListView
                    ref={el => this.lv = el}
                    dataSource={this.state.dataSource}
                    renderFooter={() => (
                        <div style={{
                            padding: 16,
                            textAlign: 'center',
                            fontSize: '13px',
                        }}>
                            {this.state.hasMore === true ? "正在加载内容..." : '没有更多内容了~'}
                        </div>)}
                    renderRow={row}
                    style={{
                        height: this.state.height,
                        overflow: 'auto',
                    }}
                    initialListSize={2000}
                    pageSize={20}
                    className="am-list"
                    onScroll={this.onScroll}
                    scrollEventThrottle={100}
                    scrollRenderAheadDistance={300}
                    onEndReached={this.onEndReached}
                    onEndReachedThreshold={20}
                />
            </div>
        );
    }
}
export default HomeAlbumList;
